package com.ruoyi.lock.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.lock.domain.AHomeUser;
import com.ruoyi.lock.service.IAHomeUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.text.ParseException;

/**
 * 入住信息Controller
 * 
 * @author ruoyi
 * @date 2025-07-25
 */
@RestController
@RequestMapping("/lock/homeUser")
public class AHomeUserController extends BaseController
{
    @Autowired
    private IAHomeUserService aHomeUserService;

    /**
     * 查询入住信息列表
     */
//    @PreAuthorize("@ss.hasPermi('lock:homeUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(AHomeUser aHomeUser)
    {
        startPage();
        List<AHomeUser> list = aHomeUserService.selectAHomeUserList(aHomeUser);
        return getDataTable(list);
    }

    /**
     * 导出入住信息列表
     */
//    @PreAuthorize("@ss.hasPermi('lock:homeUser:export')")
    @Log(title = "入住信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AHomeUser aHomeUser)
    {
        List<AHomeUser> list = aHomeUserService.selectAHomeUserList(aHomeUser);
        ExcelUtil<AHomeUser> util = new ExcelUtil<AHomeUser>(AHomeUser.class);
        util.exportExcel(response, list, "入住信息数据");
    }

    /**
     * 获取入住信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('lock:homeUser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(aHomeUserService.selectAHomeUserById(id));
    }

    /**
     * 新增入住信息
     */
//    @PreAuthorize("@ss.hasPermi('lock:homeUser:add')")
    @Log(title = "入住信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AHomeUser aHomeUser)
    {
        return toAjax(aHomeUserService.insertAHomeUser(aHomeUser));
    }

    /**
     * 修改入住信息
     */
    @PreAuthorize("@ss.hasPermi('lock:homeUser:edit')")
    @Log(title = "入住信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AHomeUser aHomeUser)
    {
        return toAjax(aHomeUserService.updateAHomeUser(aHomeUser));
    }

    /**
     * 删除入住信息
     */
    @PreAuthorize("@ss.hasPermi('lock:homeUser:remove')")
    @Log(title = "入住信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aHomeUserService.deleteAHomeUserByIds(ids));
    }

    /**
     * 批量新增入住信息
     */
    @PostMapping("/batchAdd")
    public AjaxResult batchAdd(@RequestBody List<AHomeUser> homeUserList) {
        int rows = aHomeUserService.batchInsertAHomeUser(homeUserList);
        return toAjax(rows);
    }

    /**
     * 批量入住接口 - 一个人入住多个房间
     */
    @PostMapping("/batchRuzhu")
    public AjaxResult batchRuzhu(@RequestBody Map<String, Object> requestData) {
        try {
            Long userId = Long.valueOf(requestData.get("userId").toString());
            List<?> roomIdsRaw = (List<?>) requestData.get("roomIds");
            String startTime = (String) requestData.get("startTime");
            String endTime = (String) requestData.get("endTime");
            
            if (userId == null || roomIdsRaw == null || roomIdsRaw.isEmpty()) {
                return AjaxResult.error("用户ID和房间ID不能为空");
            }
            
            // 转换房间ID为Long类型
            List<Long> roomIds = new ArrayList<>();
            for (Object roomIdObj : roomIdsRaw) {
                if (roomIdObj instanceof Integer) {
                    roomIds.add(((Integer) roomIdObj).longValue());
                } else if (roomIdObj instanceof Long) {
                    roomIds.add((Long) roomIdObj);
                } else {
                    roomIds.add(Long.valueOf(roomIdObj.toString()));
                }
            }
            
            // 验证时间参数
            if (startTime == null || startTime.trim().isEmpty()) {
                return AjaxResult.error("开始时间不能为空");
            }
            if (endTime == null || endTime.trim().isEmpty()) {
                return AjaxResult.error("结束时间不能为空");
            }
            
            // 解析时间字符串
            Date startDate;
            Date endDate;
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startDate = sdf.parse(startTime);
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                return AjaxResult.error("时间格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式");
            }
            
            List<AHomeUser> homeUserList = new ArrayList<>();
            for (Long roomId : roomIds) {
                AHomeUser homeUser = new AHomeUser();
                homeUser.setUserId(userId);
                homeUser.setHomeId(roomId);
                homeUser.setStartTime(startDate);
                homeUser.setEndTime(endDate);
                homeUserList.add(homeUser);
            }
            
            int rows = aHomeUserService.batchInsertAHomeUser(homeUserList);
            return AjaxResult.success("批量入住成功，共入住 " + rows + " 个房间");
        } catch (Exception e) {
            return AjaxResult.error("批量入住失败：" + e.getMessage());
        }
    }
}
